layui.use('table', function (){
    var table = layui.table;
    //第一个实例
    table.render({
        elem: "#demo"
        , url:'/findClassroom'
        , method: 'post'
        , page: true //开启分页
        , toolbar: 'default' //开启工具栏，此处显示默认图标，可以自定义模板，详见文档
        , limit: 7
        , id:'testReload'
        , limits: [3, 5, 7]
        , cols: [[
            { field: 'pkId',width: 80, type: 'checkbox' },
            { field: 'region', width: 185,title: '区域', sort: true,},
            { field: 'buildingNo', width: 185,title: '楼号' },
            { field: 'buildingFloor', width: 185,title: '楼层' },
            { field: 'classroomNumber', width: 185,title: '教室编号', sort: true },
            { field: 'classroomName', width: 185,title: '教室名称' },
            { field: 'useStatus', width: 185,title: '使用状态' },
            { field: 'galleryful', width: 185,title: '容纳人数', sort: true },
            { field: 'createdate', width: 205,title: '创建时间', sort: true },
            { field: 'updatedate', width: 205,title: '修改时间' },
            { field: 'right', width: 110, title: '操作', toolbar: '#barDemo' },
        ]],
        done: function (res, curr, count){
            $("[data-field='useStatus']").children().each(function () {
                if ($(this).text() == 'true') {
                    $(this).text("已使用");
                } else if ($(this).text() == 'false') {
                    $(this).text("未使用");
                }
            });
        },
        parseData: function (res) { //将原始数据解析成 table 组件所规定的数据
            return {
                "code": res.code, //解析接口状态
                "msg": res.msg, //解析提示文本
                "count": res.count, //解析数据长度
                "data": res.data //解析数据列表
            };
        },
        request: {
            pageName: 'page' // 页码的参数名称，默认：page
            , limitName: 'limit' //每页数据量的参数名，默认：limit
        },
    });
    //升序降序后重新渲染
    table.on('sort(test)', function(obj) {
        table.reload('testReload', {
            initSort: obj
        });
    });
    table.reload('testReload', {});
    //表单数据重载
    var $ = layui.$,active = {
        reload : function (){
            var classroomNumber = $("#classroomNumber");
            var classroomName = $("#classroomName");
            var galleryfulMin = $("#galleryfulMin");
            var galleryfulMax = $("#galleryfulMax");
            var buildingFloor = $("#buildingFloor");
            var buildingNo = $("#buildingNo");
            var region = $("#region");
            //执行重载
            table.reload('testReload',{
                page: {
                    curr : 1 //重新从第一页开始
                },
                where:{
                    classroomName:classroomName.val(),
                    galleryfulMin:galleryfulMin.val(),
                    classroomNumber:classroomNumber.val(),
                    galleryfulMax:galleryfulMax.val(),
                    buildingFloor:buildingFloor.val(),
                    buildingNo:buildingNo.val(),
                    region:region.val(),
                }
            });
        }
    };
    $('.demoTable .layui-btn').on('click',function (){
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });

    // //监听头工具事件
    table.on('toolbar(test)', function(obj){
        var checkStatus = table.checkStatus(obj.config.id)
            ,data = checkStatus.data //获取选中的数据
            ,delList=[];
        for(var i=0;i<data.length;i++){
            delList.push(data[i].pkId);
        }

        var json={"pkIds":delList};
        switch(obj.event) {
            case 'add':
                layer.msg('添加');
                layer.open({
                    type: 1 //此处以iframe举例
                    , title: '班级信息录入表'
                    , area: ['800px', '650px']
                    , shade: 0
                    , maxmin: true
                    , content: $("#insertPage")
                })

                $("#insertClassroom").click(function (){
                    var istData = {
                        "region":$("#istregion").val(),
                        "buildingNo":$("#istbuildingNo").val(),
                        "buildingFloor":$("#istbuildingFloor").val(),
                        "classroomId":$("#istclassroomId").val(),
                        "classroomNumber":$("#istclassroomNumber").val(),
                        "classroomName":$("#istclassroomName").val(),
                        "galleryful":$("#istgalleryful").val(),
                    }
                    $.ajax({
                        type:"post",
                        url:"/insertSelective",
                        data:JSON.stringify(istData),
                        contentType: "application/json;charset=utf-8",
                        dataType:"json",
                        success:function (istData) {
                            if(istData=='1'){
                                layer.msg('添加成功',{icon:6,time:1000},function () {
                                    window.location.reload();
                                })
                            }else if(istData=='0'){
                                layer.msg('添加失败',{icon:5,time:1000},function () {
                                    window.location.reload();
                                })
                            }
                        },error:function (error) {
                            layer.msg("添加请求失败")
                        }

                    });
                })
                break;
            case 'update':
                if(data.length === 0){
                    layer.msg('请选择一行');
                } else if(data.length > 1){
                    layer.msg('只能同时编辑一个');
                } else {
                    layer.alert('编辑 [id]：'+ checkStatus.data[0].id);
                }
                break;
            case 'delete':
                if(data.length === 0){
                    layer.msg('请选择一行');
                } else {
                    layer.msg('删除');
                    $.ajax({                //批量删除
                        type:"post",
                        url:"/deleteByPrimaryKey",
                        contentType: "application/json;charset=utf-8",
                        data:JSON.stringify(json),
                        dataType:"json",
                        success:function (delData) {
                            if(delData > 0){
                                layer.msg('删除成功',{icon:6,time:1000},function () {
                                    window.location.reload();
                                })
                            }else if(delData < 1) {
                                layer.msg('删除失败', {icon: 5, time: 1000}, function () {
                                    window.location.reload();
                                })
                            }
                        },error:function (error) {
                            layer.msg("删除请求失败");
                        }
                    })
                }
                break;
        };
    });
    //区域楼号楼层下拉框
    $.ajax({
        type:"post",
        url:"/region",
        contentType: "application/json;charset=utf-8",
        dataType:"json",
        success:function (regions) {
            var $regiones="<option value=''>请选择</option>";
            for(var i=0;i<regions.length;i++) {
                $regiones+="<option value="+regions[i].region+">"+regions[i].region+"</option>"
            }
            $("select[name='istregion']").html($regiones);

            //当select发生改变时
            $("select[name='istregion']").change(function() {
                $("#buildingNo").empty();
                if ( $("select[name='istregion'] option:selected").text() == "A区") {
                    var $QINGXUANZE ="<option ></option>";
                    $("#buildingNo").append($QINGXUANZE);
                    for(let i = 1;i<=5;i++){
                        var $data = $("<option >" + i + "号</option>");
                        $("#buildingNo").append($data);
                    }
                }
                if ( $("select[name='istregion'] option:selected").text() == "B区") {
                    var $QINGXUANZE ="<option ></option>";
                    $("#buildingNo").append($QINGXUANZE);
                    for(let i = 6;i<=10;i++){
                        var $data = $("<option >" + i+ "号</option>");
                        $("#buildingNo").append($data);
                    }
                }
                if ( $("select[name='istregion'] option:selected").text() == "C区") {
                    var $QINGXUANZE ="<option></option>";
                    $("#buildingNo").append($QINGXUANZE);
                    for(let i = 11;i<=15;i++){
                        var $data = $("<option >" + i+ "号</option>");
                        $("#buildingNo").append($data);
                    }
                }
                if ( $("select[name='istregion'] option:selected").text() == "D区") {
                    var $QINGXUANZE ="<option ></option>";
                    $("#buildingNo").append($QINGXUANZE);
                    for(let i = 16;i<=20;i++){
                        var $data = $("<option >" + i+ "号</option>");
                        $("#buildingNo").append($data);
                    }

                }
                layui.form.render('select');
            })
            $("select[name='istbuildingNo']").change(function() {
                $("#buildingFloor").empty();
                let buildingNo = $("#buildingNo").val();
                $.get("",function(){
                    var $QINGXUANZE ="<option></option>";
                    $("#buildingFloor").append($QINGXUANZE);
                    for(let i = 1;i<=12;i++){
                        var $data = $("<option >" +i + "层</option>");
                        $("#buildingFloor").append($data);
                    }
                    layui.form.render('select');
                })
            })
        },error:function (error) {
            layer.msg("添加请求失败1");
        }
    });
    //监听行工具事件
    table.on('tool(test)', function(obj){ //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
        var data = obj.data //获得当前行数据
            ,layEvent = obj.event //获得 lay-event 对应的值
            ,dropdown=layui.dropdown;
        if(layEvent === 'detail') {
            layer.msg('查看操作');
        } else if(layEvent === 'more'){
            //下拉菜单
            dropdown.render({
                elem: this //触发事件的 DOM 对象
                ,show: true //外部事件触发即显示
                ,data: [{
                    title: '编辑'
                    ,id: 'edit'
                },{
                    title: '删除'
                    ,id: 'del'
                }]
                ,click: function(menudata){
                    if(menudata.id === 'del'){
                        layer.confirm('真的删除行么', function(index){
                            obj.del(); //删除对应行（tr）的DOM结构
                            //layer.close(index);
                            //向服务端发送删除指令
                            $.ajax({
                                type:'post',
                                url:"/classroomDelete",
                                data:JSON.stringify(data),
                                contentType:'application/json;charset=utf-8',
                                dataType:"json",
                                success:function (classroom) {
                                    if(classroom=='1'){
                                        layer.msg('删除成功',{icon:6,time:1000},function () {
                                            window.location.reload();
                                        })
                                    }else if(classroom=='0'){
                                        layer.msg('删除失败',{icon:5,time:1000},function () {
                                            window.location.reload();
                                        })
                                    }
                                },error:function (error) {
                                    alert("请求失败")
                                }
                            })
                        });
                    } else if(menudata.id === 'edit'){
                        layer.msg('编辑操作，当前行 ID:'+ data.pkId);
                        layer.open({
                            type: 1 //此处以iframe举例
                            , title:'教室'+data.classroomName+'的信息'
                            , area: ['800px', '600px']
                            , shade: 0
                            , maxmin: true
                            ,content:$("#updatePage")
                        })
                        //数据回显
                        $("#upregion").val(data.region),//区域
                            $("#upbuildingNo").val(data.buildingNo),//楼号
                            $("#upbuildingFloor").val(data.buildingFloor),//楼层
                            $("#upclassroomId").val(data.classroomName),//教室id
                            $("#upclassroomNumber").val(data.classroomNumber),//教室编号
                            $("#upclassroomName").val(data.classroomName),//教室名称
                            $("#upgalleryful").val(data.galleryful),//容纳人数

                            $("#updDetailAddr").val(data.detailAddr);//详细信息

                        $("#updateClassroom").click(function () {
                            var updData={
                                "pkId":data.pkId,
                                "region":$("#upregion").val(),
                                "buildingNo":$("#upbuildingNo").val(),
                                "buildingFloor":$("#upbuildingFloor").val(),
                                "classroomId":$("#upclassroomId").val(),
                                "classroomNumber":$("#upclassroomNumber").val(),
                                "classroomName":$("#upclassroomName").val(),
                                "galleryful":$("#upgalleryful").val(),
                            }
                            $.ajax({
                                type:"post",
                                url:"/updateByPrimaryKeySelective",
                                data:JSON.stringify(updData),
                                contentType: "application/json;charset=utf-8",
                                dataType:"json",
                                success:function (upData) {
                                    if(upData=='1'){
                                        layer.msg('修改成功',{icon:6,time:1000},function () {
                                            window.location.reload();
                                        })
                                    }else if(upData=='0'){
                                        layer.msg('修改失败',{icon:5,time:1000},function () {
                                            window.location.reload();
                                        })
                                    }
                                },error:function (error) {
                                    layer.msg("修改请求失败")
                                }

                            })
                        })


                    }
                }
                ,align: 'right' //右对齐弹出（v2.6.8 新增）
                ,style: 'box-shadow: 1px 1px 10px rgb(0 0 0 / 12%);' //设置额外样式
            })
        }
    });
});